﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;
using System.Threading.Tasks;
using WebApiOrm.Provider.EFCoreSqlite;

namespace WebApiOrm.Controllers
{
    /// <summary>
    /// 数据库控制器
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class DatabasesController : ControllerBase
    {
        private readonly EFCoreDbContext context;

        /// <summary>
        /// 数据库控制器
        /// </summary>
        /// <param name="context"></param>
        public DatabasesController(EFCoreDbContext context)
        {
            this.context = context;
        }

        /// <summary>
        /// 清除数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("clear")]
        public async Task<int> Clear()
        {
            var db = context.Database;
            var connection = db.GetDbConnection();
            if (connection.State != ConnectionState.Open)
            {
                await connection.OpenAsync();
            }

            if (db.IsSqlite())
            {
                using var delete = connection.CreateCommand();
                delete.CommandText = "delete from SysUser";
                var count = await delete.ExecuteNonQueryAsync();

                using var vacuum = connection.CreateCommand();
                vacuum.CommandText = "VACUUM";
                await vacuum.ExecuteNonQueryAsync();

                return count;
            }
            else
            {
                using var truncate = connection.CreateCommand();
                truncate.CommandText = db.IsNpgsql()
                    ? "truncate table \"SysUser\""
                    : "truncate table SysUser";
                return await truncate.ExecuteNonQueryAsync();
            }
        }
    }
}
